#!/bin/env python
"""

Issues:
 - The URL passed to ServerProxy should come from a config file
 - The file containing the server cert trust change should come from a config file
"""
from common import *
import ConfigParser as config
import getpass
import httplib
from optparse import OptionParser
import pdb
import pprint
from qnaire import Questionnaire
import socket
import sys
import xmlrpclib
import uuid
from SXR_client import *

def main(args):

    p = OptionParser()
    p.add_option('-d', '--debug',
                 action='store_true', default=False, dest='debug',
                 help="run under debugger")
    p.add_option('-S', '--testssl',
                 action='store_true', default=False, dest='testssl',
                 help="make a test connection to the server")
    (o, a) = p.parse_args(sys.argv)

    if o.debug:
        pdb.set_trace()

    cfg = get_config('bundler.cfg')
    hostname = cfg.get('DEFAULT', 'hostname')
    port = cfg.get('DEFAULT', 'port')
    
    if o.testssl:
        server = xmlrpclib.ServerProxy('https://%s:%s' % (hostname, port),
                                       TLSv1Transport())
        if server.testssl():
            print("connection succeeded")
        else:
            print("test connection failed")
        sys.exit(0)
        
    openid = raw_input("Please type or paste your ESGF openid\n> ")
    validate_openid(openid)
    passwd = getpass.getpass("Password: ")

    #
    # get credential by calling myproxy-logon script
    #
    go_dir = cfg.get('DEFAULT', 'go_dir')
    rc = fetch_credential(openid, passwd, go_dir)
    if not rc:
        print("Sorry, the attempt to fetch an ESG credential for you failed")
        print("   openid: %s" % openid)
        sys.exit(1)

    #
    # connect to pub service and authenticate
    #
    server = xmlrpclib.ServerProxy('https://%s:%s' % (hostname, port),
                                   TLSv1Transport())
    rc = server.auth(openid, passwd)
    auth_token = uuid.UUID(rc)
    if auth_token == uuid.UUID('0' * 32):
        print("Sorry, you don't appear to have publisher privileges.")
        sys.exit(1)

    print("auth was successful")

    #
    # run the questionnaire to collect the user's input
    #
    Q = Questionnaire('metadata.qn')
    rsp = Q.ask()
    Q.save('metadata.rsp')

    #
    # send data locations to server
    # '010'  => GO username
    # '020' => data location 'remote' or 'local'
    # '030' => GO endpoint for data
    # '032' => GO path to data on endpoint
    # '040' => local path to data
    # '050' => e-mail address or empty
    # '060' => nothing
    #
    go_username = Q.cf.get('010', 'answer')
    data_loc = Q.cf.get('020', 'answer')   # 'local' or 'remote'
    if data_loc == 'remote':
        go_ep = Q.cf.get('030', 'answer')
        path = Q.cf.get('032', 'answer')
    elif data_loc == 'local':
        go_ep = ''
        path = Q.cf.get('040', 'answer')
    else:
        raise StandardException("Data location ('%s') should be 'local' or remote'"
                                % data_loc)
    server.goxfr(auth_token.hex, go_username, go_ep, path)

    # here the bundler must background itself and monitor the tranfers
    # until they complete, then clean up the local endpoint.
    
if __name__ == '__main__':
    main(sys.argv)
